<?php

namespace app\mobile\controller;

use think\Controller;

use think\Request;
use think\Session;
use \think\Db;

use app\api\model\User as UserModel;

use app\mobile\extra\phpqucode;
use app\common\library\wechat\WxPayTwo;
use app\common\library\wechat\WxPay;
use app\common\library\wechat\WeChatPay;
use app\common\library\wechat\WxpayService;
class Perpage extends Base
{
	private $urlHeader = '';

	/**提交检查首页*/
	public function index(){
		//echo Session::get('openId');
		$model = new UserModel;
		$userInfo = $model->getUserInfo(Session::get('openId'));
		$this->urlHeader = request()->domain();
		
		$other = array('YU'=>$this->urlHeader, 'wxappid'=>Config('wxappid'));
		
		return $this->fetch('index', compact('userInfo', 'other'));
	}
	
	/**提交检查函数*/
	public function ajaxForm(){
		$request = Request::instance();
		$post = $request->param();
		
		$data['c_uid'] = $post['introID'];
		$data['c_nickName'] = $post['introNickName'];
		$data['c_avatarUrl'] = $post['introAvatarUrl'];
		$data['c_orderNo'] = "pr".$post['introID'].date('YmdHis').substr(microtime(), 2, 5) . mt_rand(100,999);
		
		$data['u_nickName'] = '未领取';
		$data['u_avatarUrl'] = '';
		$data['u_trueName'] = $post['trueName'];
		$data['u_mobile'] = $post['mobile'];
		$data['u_sex'] = $post['sex'];
		$data['u_address'] = $post['address'];
		$data['r_allPrice'] = $post['allPrice'];
		$data['u_project'] = implode(',', $post['resProNameArr']);
		
		$data['r_payType'] = $post['paytype'];
		if($post['paytype']==1 || $data['r_allPrice']==0){
			$data['r_payFont'] = '线下支付';
			$data['r_payState'] = 8;
			$data['r_state'] = 20;
		}
		$data['r_wxapp_id'] = Config('wxappid');
		$data['r_createtime'] = date('Y-m-d H:i:s', time());
		
		$data['r_id']  = Db::name('order_wxpage')->insertGetId($data);
		
		return ajaxSuccessObj($data);
	}
	
	/**提交检查列表*/
	public function createlist(){
		$model = new UserModel;
		$userInfo = $model->getUserInfo(Session::get('openId'));
		$uid = $userInfo['user_id'];
		
		$other = array('YU'=>$this->urlHeader, 'wxappid'=>Config('wxappid'));
		// pre($uid); exit;
		
		$createList = Db::name('order_wxpage')->where('c_uid','=',$uid)->order('r_id desc')->limit(0,30)->select();

		// pre($createList); exit;
		return $this->fetch('createlist', compact('userInfo', 'other', 'createList'));
	}
	
	/**ajax获取订单的二维码*/
	public function getOrderImg(){
		import('phpqrcode', EXTEND_PATH);
		
		$request = Request::instance();
		$post = $request->param();
		
		$errorCorrectionLevel = 'L';//容错级别
		$matrixPointSize = 10;//生成图片大小
		
		$value = request()->domain().'/'.url('mobile/perpage/orderdes',['rid'=>$post['r_id'],'t'=>time()]);

		$imgName = "ord_{$post['r_id']}.png";
		$imgPath = "./uploads/pageorderimg/".$imgName ;

		$myBack =  \QRcode::png($value, $imgPath, $errorCorrectionLevel, $matrixPointSize, 2);
		$imgPath2 = "/uploads/pageorderimg/".$imgName.'?v='.time() ;

		$data['imgPath'] = $imgPath2;
		$data['r_id'] = $post['r_id'];
		$data['project'] = $post['u_project'];
		return ajaxSuccessObj($data);
	}
	/**ajax获取公众号推广码，关注公众号后，才弹出图文消息，进入个人订单*/
	public function getGuzhuImg(){
		// import('wechatFun', EXTEND_PATH);
		$request = Request::instance();
		$post = $request->param();
		
		$wxFun = new \wechatFun(Config('appId'), Config('appSecret'));
		$erweiMa = $wxFun->create_qrcode('QR_SCENE22',$post['r_id']);
		
		$data['allRes'] = $erweiMa;
		$data['imgPath'] = $erweiMa['imgUrl'];
		$data['r_id'] = $post['r_id'];
		$data['project'] = $post['u_project'];
		return ajaxSuccessObj($data);
	}
	
	/**展示订单的详情，谁扫描，则第一个绑定谁*/
	public function orderdes(){
		$request = Request::instance();
		$para = $request->param();
		
		// 获取到扫码人的登录用户信息
		$model = new UserModel;
		$userInfo = $model->getUserInfo(Session::get('openId'));
		
		
		// 查找此订单的信息
		$orderDes = [];
		$tipFont = "";
		$bodyFont = "";
		// 先查找用户的个人信息
		if($userInfo['nickName']=='微信用户'){
			$bodyFont = "请点击右下角使用完整服务";
		}
		// 只有点击了用户授权，才能进行相应的绑定操作
		else{
			$bodyFont = "";
			if(isset($para['rid']) && $para['rid']>0){
				$orderDes = Db::name('order_wxpage')->where('r_id','=',$para['rid'])->find();
				if(!isset($orderDes['u_uid'])){
					$tipFont = "您当前扫描的订单不存在或已被别人绑定";
				}
				//	如果没有绑定，则直接绑定，如果有绑定则不要绑定，自己不能绑定自己
				if($orderDes['u_uid']==0 && $orderDes['c_uid']!=$userInfo['user_id']){
					$updateArr['u_uid'] = $userInfo['user_id'];
					$updateArr['u_nickName'] = $userInfo['nickName'];
					$updateArr['u_avatarUrl'] = $userInfo['avatarUrl'];
					$updateArr['r_sendGiftTime'] = date('Y-m-d H:i:s', time());
					Db::name('order_wxpage')->where('r_id','=',$para['rid'])->update($updateArr);
					$orderDes = Db::name('order_wxpage')->where('r_id','=',$para['rid'])->find();
					
					$tipFont = "";
					// 修改该注册用户的信息，添加真实姓名，手机号，地址，性别等
					$update22['true_name'] = $orderDes['u_trueName'];
					$update22['true_mobile'] = $orderDes['u_mobile'];
					$update22['gender'] = $orderDes['u_sex'];
					$update22['address'] = $orderDes['u_address'];
					Db::name('user')->where('user_id','=',$userInfo['user_id'])->update($update22);
				}
				if($orderDes['u_uid']!=$userInfo['user_id']){
					$tipFont = "您当前扫描的订单已被'{$orderDes['u_nickName']}'绑定";
				}
				else{
					$tipFont = "";
				}
			}
		}
		
		// 查找属于自己的专属订单
		$_myList = Db::name('order_wxpage')->where('u_uid','=',$userInfo['user_id'])->order('r_id desc')->limit(0,30)->select();
		$myList = count($_myList)>0 ? $_myList : [];
		//pre($myList); exit;
		$other = array('YU'=>$this->urlHeader, 'wxappid'=>Config('wxappid'), 'tipFont'=>$tipFont, 'bodyFont'=>$bodyFont);
		return $this->fetch('orderdes', compact('orderDes', 'other', 'myList'));
		
	}
	
	/**构建支付订单*/
	public function toPayOrder(){
		$request = Request::instance();
		$para = $request->param();
		$uid = $para['u_uid'];
		$oid = $para['r_id'];
		
		$model = new UserModel;
		$userInfo = $model->getUserInfo(Session::get('openId'));
		
		$orderInfo = Db::name('order_wxpage')->where('r_id','=',$para['r_id'])->find();

		$orderNo = $orderInfo['c_orderNo'];
		$payPrice = $orderInfo['r_allPrice'];
		
		$wxConfig['app_id'] = Config('appId');
		$wxConfig['app_secret'] = Config('appSecret');
		$wxConfig['mchid'] = Config('MCHID');
		$wxConfig['apikey'] = Config('KEY');
		$wxConfig['wxapp_id'] = $userInfo['wxapp_id'];
	/*	
		$WxPay = new WxPay($wxConfig);
		$payment = $WxPay->unifiedorder($orderNo, Session::get('openId'), $payPrice);
*/

		$weChatPay = new WeChatPay($wxConfig['app_id'], $wxConfig['mchid'], $wxConfig['apikey']);
		$params = array(
			'body' => $orderInfo['u_project'],
			'out_trade_no' => $orderNo,
			'total_fee' => $payPrice*100,
			'spbill_create_ip' => request()->ip(),
			'notify_url' => base_url() . 'notice.php',
			'trade_type' => 'JSAPI',
			'openid' => Session::get('openId'),
		);
		$payment = $weChatPay->unifiedOrder($params);



		$params['paySign'] = $payment['sign'];
		$params['timeStamp']=time();
		
		$data['config'] = $wxConfig;
		$data['payment'] = $payment;
		$data['params'] = $params;
		return ajaxSuccessObj($data);
	}

	public function pay(){
		$r_id = input('r_id');
		$mchid = Config('MCHID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
		$appid = Config('appId');  //微信支付申请对应的公众号的APPID
		$appKey = Config('appSecret');;   //微信支付申请对应的公众号的APP Key
		$apiKey = Config('KEY');   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

		//①、获取用户openid
		$wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey);
		//$openId = $wxPay->GetOpenid();      //获取openid
		//if(!$openId) exit('获取openid失败');

		$openId = Session::get('openId');
		$orderInfo = Db::name('order_wxpage')->where('r_id','=',$r_id)->find();

		$orderInfo['c_orderNo'] = "pr".$orderInfo['c_uid'].date('YmdHis').substr(microtime(), 2, 5) . mt_rand(100,999);

		Db::name('order_wxpage')->where('r_id','=',$r_id)->update([
			'c_orderNo'=>$orderInfo['c_orderNo']
		]);

		//②、统一下单
		$outTradeNo = $orderInfo['c_orderNo'];     //你自己的商品订单号
		$payAmount = $orderInfo['r_allPrice'];          //付款金额，单位:元
		$orderName = $orderInfo['u_project'];    //订单标题
		$notifyUrl = base_url() . 'index.php/mobile/Notify/order';     //付款成功后的回调地址(不要有问号)
		$payTime = time();      //付款时间
		$jsApiParameters = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);
		$jsApiParameters = json_encode($jsApiParameters);
		$this->assign('jsApiParameters',$jsApiParameters);
		$this->assign('orderInfo',$orderInfo);
		return $this->fetch('pay');
	}

}